package com.itheima.reggie.filter;

import cn.hutool.core.net.url.UrlPath;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserIdThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求:{}",requestURI);
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                 "/user/login",
                  "/user/sendMsg"};
        //2、判断本次请求是否需要处理
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            //3、如果不需要处理，则直接放行
            if (match){
                log.info("本次请求为{}，不需要拦截",requestURI);
                filterChain.doFilter(request,response);
                return;
            }
        }
        //4、判断登录状态，如果已登录，则直接放行
        if (session.getAttribute("employee") != null){
            log.info("员工已登录");
            Long employeeId = (Long) session.getAttribute("employee");
            //记录登录id
            UserIdThreadLocal.setId(employeeId);
            filterChain.doFilter(request,response);
            //删除登录id
            UserIdThreadLocal.removeId();
            return;
        }
        //5.判断用户登录状态
        if (session.getAttribute("userId") != null){
            log.info("用户已登录");
            Long userId = (Long) session.getAttribute("userId");
            UserIdThreadLocal.setId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        log.info("用户未登录");
        R r = R.error("NOTLOGIN");
        response.getWriter().write(JSON.toJSONString(r));
    }

}
